# PS1转EXE可视化工具 - PS2EXE简洁版
# 版本: 2.4 (简洁匀称版)
# 作者: 向日葵 (PS2EXE简洁版)
# 描述: 修复界面问题，简洁匀称的界面设计

# 要求管理员权限运行
#Requires -RunAsAdministrator

# 严格的权限检查
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "此脚本需要管理员权限运行，正在重新启动..." -ForegroundColor Yellow
    Start-Process PowerShell -Verb RunAs "-File `"$PSCommandPath`""
    exit
}

# 设置执行策略和编码
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
chcp 65001 | Out-Null

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# 全局变量
$global:inputFile = ""
$global:outputFile = ""
$global:iconFile = ""

# 创建简洁按钮
function New-SimpleButton {
    param(
        [string]$text,
        [System.Drawing.Point]$location,
        [System.Drawing.Size]$size,
        [string]$colorType = "Primary"
    )
    
    $colors = @{
        Primary = [System.Drawing.Color]::FromArgb(41, 128, 185)
        Success = [System.Drawing.Color]::FromArgb(39, 174, 96)
        Warning = [System.Drawing.Color]::FromArgb(243, 156, 18)
        Danger = [System.Drawing.Color]::FromArgb(231, 76, 60)
        Purple = [System.Drawing.Color]::FromArgb(142, 68, 173)
        Info = [System.Drawing.Color]::FromArgb(52, 152, 219)
    }
    
    $button = New-Object System.Windows.Forms.Button
    $button.Text = $text
    $button.Location = $location
    $button.Size = $size
    $button.Font = New-Object System.Drawing.Font("Microsoft YaHei UI", 10, [System.Drawing.FontStyle]::Bold)
    $button.BackColor = $colors[$colorType]
    $button.ForeColor = [System.Drawing.Color]::White
    $button.FlatStyle = [System.Windows.Forms.FlatStyle]::Flat
    $button.FlatAppearance.BorderSize = 1
    $button.FlatAppearance.BorderColor = $colors[$colorType]
    $button.Cursor = [System.Windows.Forms.Cursors]::Hand
    $button.UseVisualStyleBackColor = $false
    
    return $button
}

# 创建GroupBox
function New-SimpleGroupBox {
    param(
        [string]$text,
        [System.Drawing.Point]$location,
        [System.Drawing.Size]$size
    )
    
    $groupBox = New-Object System.Windows.Forms.GroupBox
    $groupBox.Text = $text
    $groupBox.Location = $location
    $groupBox.Size = $size
    $groupBox.Font = New-Object System.Drawing.Font("Microsoft YaHei UI", 11, [System.Drawing.FontStyle]::Bold)
    $groupBox.ForeColor = [System.Drawing.Color]::FromArgb(52, 73, 94)
    $groupBox.BackColor = [System.Drawing.Color]::White
    $groupBox.Anchor = [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right
    
    return $groupBox
}

# 创建标签
function New-SimpleLabel {
    param(
        [string]$text,
        [System.Drawing.Point]$location,
        [System.Drawing.Size]$size,
        [int]$fontSize = 10
    )
    
    $label = New-Object System.Windows.Forms.Label
    $label.Text = $text
    $label.Location = $location
    $label.Size = $size
    $label.Font = New-Object System.Drawing.Font("Microsoft YaHei UI", $fontSize)
    $label.ForeColor = [System.Drawing.Color]::FromArgb(52, 73, 94)
    $label.BackColor = [System.Drawing.Color]::Transparent
    
    return $label
}

# 创建文本框
function New-SimpleTextBox {
    param(
        [System.Drawing.Point]$location,
        [System.Drawing.Size]$size,
        [string]$text = "",
        [bool]$readOnly = $false
    )
    
    $textBox = New-Object System.Windows.Forms.TextBox
    $textBox.Location = $location
    $textBox.Size = $size
    $textBox.Font = New-Object System.Drawing.Font("Microsoft YaHei UI", 10)
    $textBox.Text = $text
    $textBox.ReadOnly = $readOnly
    $textBox.BackColor = [System.Drawing.Color]::White
    $textBox.BorderStyle = [System.Windows.Forms.BorderStyle]::FixedSingle
    $textBox.Anchor = [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right
    
    return $textBox
}

# 创建下拉框
function New-SimpleComboBox {
    param(
        [System.Drawing.Point]$location,
        [System.Drawing.Size]$size,
        [string[]]$items = @()
    )
    
    $comboBox = New-Object System.Windows.Forms.ComboBox
    $comboBox.Location = $location
    $comboBox.Size = $size
    $comboBox.Font = New-Object System.Drawing.Font("Microsoft YaHei UI", 10)
    $comboBox.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList
    $comboBox.BackColor = [System.Drawing.Color]::White
    
    foreach ($item in $items) {
        $comboBox.Items.Add($item) | Out-Null
    }
    
    if ($items.Count -gt 0) {
        $comboBox.SelectedIndex = 0
    }
    
    return $comboBox
}

# 创建复选框
function New-SimpleCheckBox {
    param(
        [string]$text,
        [System.Drawing.Point]$location,
        [System.Drawing.Size]$size,
        [bool]$checked = $false
    )
    
    $checkBox = New-Object System.Windows.Forms.CheckBox
    $checkBox.Text = $text
    $checkBox.Location = $location
    $checkBox.Size = $size
    $checkBox.Font = New-Object System.Drawing.Font("Microsoft YaHei UI", 10)
    $checkBox.ForeColor = [System.Drawing.Color]::FromArgb(52, 73, 94)
    $checkBox.BackColor = [System.Drawing.Color]::Transparent
    $checkBox.Checked = $checked
    
    return $checkBox
}

# 状态更新函数
function Update-Status {
    param([string]$message, [string]$colorType = "Primary")
    
    $colors = @{
        Primary = [System.Drawing.Color]::FromArgb(41, 128, 185)
        Success = [System.Drawing.Color]::FromArgb(39, 174, 96)
        Warning = [System.Drawing.Color]::FromArgb(243, 156, 18)
        Danger = [System.Drawing.Color]::FromArgb(231, 76, 60)
    }
    
    if ($script:statusLabel) {
        $script:statusLabel.Text = $message
        $script:statusLabel.ForeColor = $colors[$colorType]
        $script:statusLabel.Refresh()
        [System.Windows.Forms.Application]::DoEvents()
    }
    
    # 同时输出到控制台
    Write-Host $message -ForegroundColor $(switch($colorType) {
        "Primary" { "Blue" }
        "Success" { "Green" }
        "Warning" { "Yellow" }
        "Danger" { "Red" }
        default { "White" }
    })
}

# 路径规范化函数
function Resolve-SafePath {
    param([string]$path)
    
    if ([string]::IsNullOrWhiteSpace($path)) {
        return ""
    }
    
    try {
        $resolvedPath = Resolve-Path -Path $path -ErrorAction Stop
        return $resolvedPath.Path
    } catch {
        try {
            $absolutePath = [System.IO.Path]::GetFullPath($path)
            return $absolutePath
        } catch {
            return $path
        }
    }
}

# PS2EXE安装函数
function Install-PS2EXE {
    try {
        Update-Status "正在配置PowerShell Gallery..." "Primary"
        
        if ((Get-PSRepository -Name 'PSGallery').InstallationPolicy -ne 'Trusted') {
            Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted
        }
        
        $psGetVersion = Get-Module PowerShellGet -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
        if ($psGetVersion.Version -lt [Version]"2.0") {
            Update-Status "正在更新PowerShellGet模块..." "Primary"
            Install-Module PowerShellGet -Force -AllowClobber -Scope CurrentUser
            Import-Module PowerShellGet -Force
        }
        
        Update-Status "正在安装PS2EXE模块..." "Primary"
        Install-Module -Name PS2EXE -Force -Scope CurrentUser -AllowClobber -Repository PSGallery
        
        Import-Module PS2EXE -Force -Global
        
        if (Get-Command "Invoke-PS2EXE" -ErrorAction SilentlyContinue) {
            Update-Status "PS2EXE模块安装并验证成功" "Success"
            return $true
        } else {
            throw "模块安装后无法找到Invoke-PS2EXE命令"
        }
        
    } catch {
        Update-Status "PS2EXE模块安装失败: $($_.Exception.Message)" "Danger"
        [System.Windows.Forms.MessageBox]::Show("PS2EXE模块安装失败:`n$($_.Exception.Message)`n`n请尝试手动执行：`nInstall-Module PS2EXE -Force", "安装失败", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
        return $false
    }
}

# 检查PS2EXE是否正确安装
function Test-PS2EXE {
    try {
        $module = Get-Module -ListAvailable -Name PS2EXE
        if ($module) {
            Import-Module PS2EXE -Force -Global
            return (Get-Command "Invoke-PS2EXE" -ErrorAction SilentlyContinue) -ne $null
        }
        return $false
    } catch {
        return $false
    }
}

# PS2EXE转换函数
function Convert-PS1ToEXE-PS2EXE-Final {
    param(
        [string]$inputFile,
        [string]$outputFile,
        [hashtable]$options
    )
    
    if (-not (Test-Path $inputFile)) {
        Update-Status "输入文件不存在" "Danger"
        [System.Windows.Forms.MessageBox]::Show("输入文件不存在: $inputFile", "文件不存在", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
        return $false
    }
    
    if (-not (Test-PS2EXE)) {
        $result = [System.Windows.Forms.MessageBox]::Show(
            "检测到未正确安装PS2EXE模块，是否自动安装？`n`n注意：需要网络连接和PowerShell Gallery访问权限", 
            "缺少转换模块", 
            [System.Windows.Forms.MessageBoxButtons]::YesNo,
            [System.Windows.Forms.MessageBoxIcon]::Question
        )
        
        if ($result -eq [System.Windows.Forms.DialogResult]::Yes) {
            if (-not (Install-PS2EXE)) {
                return $false
            }
        } else {
            Update-Status "取消转换：需要PS2EXE模块" "Warning"
            return $false
        }
    }
    
    try {
        Update-Status "正在使用PS2EXE转换，请稍候..." "Primary"
        
        $outputDir = Split-Path $outputFile -Parent
        if (-not (Test-Path $outputDir)) {
            New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
        }
        
        if (Test-Path $outputFile) {
            Remove-Item $outputFile -Force
        }
        
        Remove-Module PS2EXE -Force -ErrorAction SilentlyContinue
        Import-Module PS2EXE -Force -Global
        
        $safeInputFile = Resolve-SafePath -path $inputFile
        $safeOutputFile = Resolve-SafePath -path $outputFile
        
        Update-Status "路径规范化完成..." "Primary"
        Write-Host "规范化输入路径: $safeInputFile" -ForegroundColor Cyan
        Write-Host "规范化输出路径: $safeOutputFile" -ForegroundColor Cyan
        
        $ps2exeParams = @{
            inputFile = $safeInputFile
            outputFile = $safeOutputFile
        }
        
        if ($options.noConsole) { 
            $ps2exeParams.noConsole = $true
        }
        
        if ($options.requireAdmin) { 
            $ps2exeParams.requireAdmin = $true
        }
        
        if ($options.architecture -eq "x86") { 
            $ps2exeParams.x86 = $true
        } elseif ($options.architecture -eq "x64") {
            $ps2exeParams.x64 = $true
        }
        
        if ($options.iconFile -and (Test-Path $options.iconFile)) { 
            $safeIconFile = Resolve-SafePath -path $options.iconFile
            $ps2exeParams.iconFile = $safeIconFile
            Write-Host "规范化图标路径: $safeIconFile" -ForegroundColor Cyan
        }
        
        if ($options.title) { 
            $ps2exeParams.title = $options.title
        }
        
        if ($options.description) { 
            $ps2exeParams.description = $options.description
        }
        
        if ($options.company) { 
            $ps2exeParams.company = $options.company
        }
        
        if ($options.version) { 
            $ps2exeParams.version = $options.version
        }
        
        if ($options.product) { 
            $ps2exeParams.product = $options.product
        }
        
        if ($options.copyright) { 
            $ps2exeParams.copyright = $options.copyright
        }
        
        Update-Status "PS2EXE参数配置完成，开始转换..." "Primary"
        
        $paramDisplay = ($ps2exeParams.GetEnumerator() | ForEach-Object { 
            if ($_.Value -eq $true) {
                "-$($_.Key)"
            } else {
                "-$($_.Key) `"$($_.Value)`""
            }
        }) -join " "
        
        Write-Host "转换参数: $paramDisplay" -ForegroundColor Cyan
        
        Update-Status "执行PS2EXE转换命令..." "Primary"
        
        Write-Host "开始调用 Invoke-PS2EXE..." -ForegroundColor Green
        Invoke-PS2EXE @ps2exeParams
        
        $timeout = 45
        $elapsed = 0
        while ($elapsed -lt $timeout -and -not (Test-Path $safeOutputFile)) {
            Start-Sleep -Seconds 1
            $elapsed++
            Update-Status "等待转换完成... ($elapsed/$timeout 秒)" "Primary"
            
            if ($elapsed % 5 -eq 0) {
                Write-Host "转换进行中... $elapsed/$timeout 秒" -ForegroundColor Yellow
            }
        }
        
        if (Test-Path $safeOutputFile) {
            $fileSize = (Get-Item $safeOutputFile).Length
            Update-Status "PS2EXE转换成功完成！文件大小: $([math]::Round($fileSize/1MB, 2)) MB" "Success"
            
            [System.Windows.Forms.MessageBox]::Show("PS2EXE转换成功完成！`n输出文件: $safeOutputFile`n文件大小: $([math]::Round($fileSize/1MB, 2)) MB", "转换成功", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information)
            
            $result = [System.Windows.Forms.MessageBox]::Show(
                "是否打开输出文件所在目录？", 
                "转换完成", 
                [System.Windows.Forms.MessageBoxButtons]::YesNo,
                [System.Windows.Forms.MessageBoxIcon]::Question
            )
            
            if ($result -eq [System.Windows.Forms.DialogResult]::Yes) {
                Start-Process "explorer.exe" -ArgumentList "/select,`"$safeOutputFile`""
            }
            
            return $true
        } else {
            Update-Status "转换失败：超时未生成输出文件" "Danger"
            [System.Windows.Forms.MessageBox]::Show("转换失败：在 $timeout 秒内未生成输出文件`n`n可能原因：`n1. PS2EXE转换过程中出错`n2. 权限不足`n3. 输出路径无效`n4. 脚本存在语法问题", "转换失败", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
            return $false
        }
        
    } catch {
        Update-Status "PS2EXE转换失败: $($_.Exception.Message)" "Danger"
        
        $errorDetail = @"
PS2EXE转换失败详细信息:

错误消息: $($_.Exception.Message)
错误类型: $($_.Exception.GetType().Name)
发生位置: $($_.InvocationInfo.ScriptLineNumber) 行

输入文件: $inputFile
输出文件: $outputFile

故障排除建议:
1. 检查路径中是否包含特殊字符
2. 确保PS2EXE模块版本最新
3. 尝试使用简短的文件名
4. 检查磁盘空间是否充足
5. 确认防病毒软件未阻止

技术详情:
$($_.ScriptStackTrace)
"@
        
        Write-Host $errorDetail -ForegroundColor Red
        [System.Windows.Forms.MessageBox]::Show($errorDetail, "转换失败详情", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
        return $false
    }
}

# 主界面函数 - 简洁匀称版
function Show-MainForm {
    $form = New-Object System.Windows.Forms.Form
    $form.Text = "PS1转EXE工具 v2.4 - 简洁版"
    $form.Size = New-Object System.Drawing.Size(1100, 700)
    $form.MinimumSize = New-Object System.Drawing.Size(900, 600)
    $form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
    $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::Sizable
    $form.MaximizeBox = $true
    $form.BackColor = [System.Drawing.Color]::FromArgb(245, 245, 245)
    $form.Icon = [System.Drawing.SystemIcons]::Application
    
    # 主标题
    $titleLabel = New-SimpleLabel "PS1转EXE专业转换工具" ([System.Drawing.Point]::new(50, 20)) ([System.Drawing.Size]::new(1000, 30)) 16
    $titleLabel.Font = New-Object System.Drawing.Font("Microsoft YaHei UI", 16, [System.Drawing.FontStyle]::Bold)
    $titleLabel.ForeColor = [System.Drawing.Color]::FromArgb(41, 128, 185)
    $titleLabel.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
    $titleLabel.Anchor = [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right
    $form.Controls.Add($titleLabel)
    
    $subtitleLabel = New-SimpleLabel "基于PS2EXE引擎 - 路径修复版，支持中文路径" ([System.Drawing.Point]::new(50, 55)) ([System.Drawing.Size]::new(1000, 20)) 11
    $subtitleLabel.ForeColor = [System.Drawing.Color]::FromArgb(149, 165, 166)
    $subtitleLabel.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
    $subtitleLabel.Anchor = [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right
    $form.Controls.Add($subtitleLabel)
    
    # 文件选择区域
    $fileGroupBox = New-SimpleGroupBox "文件选择" ([System.Drawing.Point]::new(50, 90)) ([System.Drawing.Size]::new(1000, 80))
    $form.Controls.Add($fileGroupBox)
    
    $inputLabel = New-SimpleLabel "选择PS1文件:" ([System.Drawing.Point]::new(20, 35)) ([System.Drawing.Size]::new(100, 25))
    $fileGroupBox.Controls.Add($inputLabel)
    
    $inputTextBox = New-SimpleTextBox ([System.Drawing.Point]::new(130, 35)) ([System.Drawing.Size]::new(750, 25)) "" $true
    $fileGroupBox.Controls.Add($inputTextBox)
    
    $btnBrowseInput = New-SimpleButton "浏览" ([System.Drawing.Point]::new(890, 33)) ([System.Drawing.Size]::new(80, 30)) "Primary"
    $btnBrowseInput.Anchor = [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Right
    $btnBrowseInput.Add_Click({
        $openDialog = New-Object System.Windows.Forms.OpenFileDialog
        $openDialog.Filter = "PowerShell脚本文件 (*.ps1)|*.ps1|所有文件 (*.*)|*.*"
        $openDialog.Title = "选择要转换的PS1文件"
        $openDialog.InitialDirectory = [Environment]::GetFolderPath([Environment+SpecialFolder]::Desktop)
        
        if ($openDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
            $inputTextBox.Text = $openDialog.FileName
            $global:inputFile = $openDialog.FileName
            
            $baseName = [System.IO.Path]::GetFileNameWithoutExtension($openDialog.FileName)
            $directory = [System.IO.Path]::GetDirectoryName($openDialog.FileName)
            $outputPath = Join-Path $directory "$baseName.exe"
            $global:outputFile = $outputPath
            
            Update-Status "已选择文件: $(Split-Path $openDialog.FileName -Leaf)，输出: $baseName.exe" "Success"
        }
    })
    $fileGroupBox.Controls.Add($btnBrowseInput)
    
    # 转换选项区域
    $optionsGroupBox = New-SimpleGroupBox "转换选项" ([System.Drawing.Point]::new(50, 190)) ([System.Drawing.Size]::new(1000, 120))
    $form.Controls.Add($optionsGroupBox)
    
    $chkNoConsole = New-SimpleCheckBox "不显示控制台窗口（GUI模式）" ([System.Drawing.Point]::new(30, 30)) ([System.Drawing.Size]::new(250, 25))
    $optionsGroupBox.Controls.Add($chkNoConsole)
    
    $chkRequireAdmin = New-SimpleCheckBox "需要管理员权限运行" ([System.Drawing.Point]::new(300, 30)) ([System.Drawing.Size]::new(200, 25))
    $optionsGroupBox.Controls.Add($chkRequireAdmin)
    
    $archLabel = New-SimpleLabel "目标架构:" ([System.Drawing.Point]::new(30, 70)) ([System.Drawing.Size]::new(80, 25))
    $optionsGroupBox.Controls.Add($archLabel)
    
    $cmbArchitecture = New-SimpleComboBox ([System.Drawing.Point]::new(120, 70)) ([System.Drawing.Size]::new(100, 25)) @("x64", "x86")
    $optionsGroupBox.Controls.Add($cmbArchitecture)
    
    $iconLabel = New-SimpleLabel "图标文件:" ([System.Drawing.Point]::new(250, 70)) ([System.Drawing.Size]::new(80, 25))
    $optionsGroupBox.Controls.Add($iconLabel)
    
    $iconTextBox = New-SimpleTextBox ([System.Drawing.Point]::new(340, 70)) ([System.Drawing.Size]::new(540, 25)) "" $true
    $optionsGroupBox.Controls.Add($iconTextBox)
    
    $btnBrowseIcon = New-SimpleButton "浏览" ([System.Drawing.Point]::new(890, 68)) ([System.Drawing.Size]::new(80, 30)) "Info"
    $btnBrowseIcon.Anchor = [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Right
    $btnBrowseIcon.Add_Click({
        $openDialog = New-Object System.Windows.Forms.OpenFileDialog
        $openDialog.Filter = "图标文件 (*.ico)|*.ico|图片文件 (*.png;*.jpg;*.bmp)|*.png;*.jpg;*.bmp|所有文件 (*.*)|*.*"
        $openDialog.Title = "选择图标文件"
        $openDialog.InitialDirectory = [Environment]::GetFolderPath([Environment+SpecialFolder]::Desktop)
        
        if ($openDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
            $iconTextBox.Text = $openDialog.FileName
            $global:iconFile = $openDialog.FileName
            Update-Status "已选择图标文件: $(Split-Path $openDialog.FileName -Leaf)" "Success"
        }
    })
    $optionsGroupBox.Controls.Add($btnBrowseIcon)
    
    # 程序信息区域
    $infoGroupBox = New-SimpleGroupBox "程序信息（可选）" ([System.Drawing.Point]::new(50, 330)) ([System.Drawing.Size]::new(1000, 140))
    $form.Controls.Add($infoGroupBox)
    
    $titleInfoLabel = New-SimpleLabel "程序标题:" ([System.Drawing.Point]::new(30, 30)) ([System.Drawing.Size]::new(80, 25))
    $infoGroupBox.Controls.Add($titleInfoLabel)
    
    $titleTextBox = New-SimpleTextBox ([System.Drawing.Point]::new(120, 30)) ([System.Drawing.Size]::new(350, 25))
    $infoGroupBox.Controls.Add($titleTextBox)
    
    $descLabel = New-SimpleLabel "程序描述:" ([System.Drawing.Point]::new(500, 30)) ([System.Drawing.Size]::new(80, 25))
    $infoGroupBox.Controls.Add($descLabel)
    
    $descTextBox = New-SimpleTextBox ([System.Drawing.Point]::new(590, 30)) ([System.Drawing.Size]::new(380, 25))
    $descTextBox.Anchor = [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right
    $infoGroupBox.Controls.Add($descTextBox)
    
    $companyLabel = New-SimpleLabel "开发公司:" ([System.Drawing.Point]::new(30, 70)) ([System.Drawing.Size]::new(80, 25))
    $infoGroupBox.Controls.Add($companyLabel)
    
    $companyTextBox = New-SimpleTextBox ([System.Drawing.Point]::new(120, 70)) ([System.Drawing.Size]::new(350, 25))
    $infoGroupBox.Controls.Add($companyTextBox)
    
    $versionLabel = New-SimpleLabel "程序版本:" ([System.Drawing.Point]::new(500, 70)) ([System.Drawing.Size]::new(80, 25))
    $infoGroupBox.Controls.Add($versionLabel)
    
    $versionTextBox = New-SimpleTextBox ([System.Drawing.Point]::new(590, 70)) ([System.Drawing.Size]::new(150, 25))
    $versionTextBox.Text = "1.0.0.0"
    $infoGroupBox.Controls.Add($versionTextBox)
    
    $copyrightLabel = New-SimpleLabel "版权信息:" ([System.Drawing.Point]::new(30, 105)) ([System.Drawing.Size]::new(80, 25))
    $infoGroupBox.Controls.Add($copyrightLabel)
    
    $copyrightTextBox = New-SimpleTextBox ([System.Drawing.Point]::new(120, 105)) ([System.Drawing.Size]::new(850, 25))
    $copyrightTextBox.Text = "Copyright © " + (Get-Date).Year + " All Rights Reserved"
    $copyrightTextBox.Anchor = [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right
    $infoGroupBox.Controls.Add($copyrightTextBox)
    
    # 按钮区域 - 居中排列
    $buttonY = 490
    $buttonWidth = 120
    $buttonHeight = 40
    $buttonSpacing = 30
    $totalButtons = 4
    $totalWidth = ($buttonWidth * $totalButtons) + ($buttonSpacing * ($totalButtons - 1))
    $startX = (1100 - $totalWidth) / 2
    
    $btnConvert = New-SimpleButton "开始转换" ([System.Drawing.Point]::new($startX, $buttonY)) ([System.Drawing.Size]::new($buttonWidth, $buttonHeight)) "Success"
    $btnConvert.Add_Click({
        if ([string]::IsNullOrWhiteSpace($inputTextBox.Text) -or [string]::IsNullOrWhiteSpace($global:inputFile)) {
            [System.Windows.Forms.MessageBox]::Show("请先选择要转换的PS1文件", "输入错误", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning)
            return
        }
        
        $options = @{
            noConsole = $chkNoConsole.Checked
            requireAdmin = $chkRequireAdmin.Checked
            architecture = $cmbArchitecture.SelectedItem
            iconFile = $iconTextBox.Text
            title = $titleTextBox.Text
            description = $descTextBox.Text
            company = $companyTextBox.Text
            product = $titleTextBox.Text
            copyright = $copyrightTextBox.Text
            version = $versionTextBox.Text
        }
        
        Convert-PS1ToEXE-PS2EXE-Final -inputFile $global:inputFile -outputFile $global:outputFile -options $options
    })
    $form.Controls.Add($btnConvert)
    
    $btnTest = New-SimpleButton "测试环境" ([System.Drawing.Point]::new($startX + ($buttonWidth + $buttonSpacing), $buttonY)) ([System.Drawing.Size]::new($buttonWidth, $buttonHeight)) "Warning"
    $btnTest.Add_Click({
        Update-Status "正在测试环境..." "Primary"
        
        $testResults = @()
        $psVersion = $PSVersionTable.PSVersion
        $testResults += "PowerShell版本: $psVersion"
        
        $execPolicy = Get-ExecutionPolicy
        $testResults += "执行策略: $execPolicy"
        
        $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
        $testResults += "管理员权限: $(if($isAdmin){'是'}else{'否'})"
        
        $hasPS2EXE = Test-PS2EXE
        $testResults += "PS2EXE模块: $(if($hasPS2EXE){'已安装'}else{'未安装'})"
        
        if ($hasPS2EXE) {
            try {
                $ps2exeVersion = (Get-Module PS2EXE -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1).Version
                $testResults += "PS2EXE版本: $ps2exeVersion"
            } catch {
                $testResults += "PS2EXE版本: 无法获取"
            }
        }
        
        try {
            $null = Invoke-WebRequest -Uri "https://www.powershellgallery.com" -TimeoutSec 5 -UseBasicParsing
            $testResults += "网络连接: 正常"
        } catch {
            $testResults += "网络连接: 异常"
        }
        
        $resultText = "环境测试结果:`n`n" + ($testResults -join "`n")
        Update-Status "环境测试完成" "Success"
        [System.Windows.Forms.MessageBox]::Show($resultText, "环境测试", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information)
    })
    $form.Controls.Add($btnTest)
    
    $btnHelp = New-SimpleButton "使用帮助" ([System.Drawing.Point]::new($startX + 2 * ($buttonWidth + $buttonSpacing), $buttonY)) ([System.Drawing.Size]::new($buttonWidth, $buttonHeight)) "Info"
    $btnHelp.Add_Click({
        $helpText = @"
PS1转EXE工具 v2.4 使用帮助

主要功能:
• 将PowerShell脚本(.ps1)转换为可执行文件(.exe)
• 基于PS2EXE引擎，稳定可靠
• 支持中文路径和特殊字符
• 支持自定义图标和程序信息

使用步骤:
1. 以管理员身份运行本工具
2. 点击"测试环境"检查系统配置
3. 选择要转换的PS1文件
4. 选择图标文件（可选）
5. 配置转换选项和程序信息
6. 点击"开始转换"

转换选项说明:
• GUI模式: 生成无控制台窗口的应用程序
• 管理员权限: 生成的EXE需要管理员权限运行
• 架构选择: x64推荐，x86兼容性更好

注意事项:
• 确保以管理员身份运行
• 首次使用会自动安装PS2EXE模块
• 转换时间根据脚本复杂度而定
• 生成的EXE文件可独立运行
"@
        [System.Windows.Forms.MessageBox]::Show($helpText, "使用帮助", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information)
    })
    $form.Controls.Add($btnHelp)
    
    $btnAbout = New-SimpleButton "关于工具" ([System.Drawing.Point]::new($startX + 3 * ($buttonWidth + $buttonSpacing), $buttonY)) ([System.Drawing.Size]::new($buttonWidth, $buttonHeight)) "Purple"
    $btnAbout.Add_Click({
        $aboutText = @"
关于PS1转EXE工具 v2.4

版本信息:
• 版本号: v2.4 (简洁版)
• 发布日期: $(Get-Date -Format 'yyyy年MM月dd日')
• 基于引擎: PS2EXE
• 支持系统: Windows 10/11

主要特性:
• 简洁匀称的界面设计
• 修复路径解析问题
• 支持中文路径和特殊字符
• 支持调整窗口大小
• 按钮居中布局

技术支持:
• 基于PS2EXE引擎 (by Markus Scholtes)
• 支持PowerShell 5.1和7.x
• 生成.NET Framework可执行文件

开发目标:
为PowerShell开发者提供简单易用、
功能完善的脚本转换工具。

© 2024 PS1转EXE工具. All Rights Reserved.
"@
        [System.Windows.Forms.MessageBox]::Show($aboutText, "关于工具", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information)
    })
    $form.Controls.Add($btnAbout)
    
    # 状态栏
    $script:statusLabel = New-Object System.Windows.Forms.Label
    $script:statusLabel.Text = "PS2EXE转换工具v2.4就绪 - 简洁版，支持中文路径"
    $script:statusLabel.Font = New-Object System.Drawing.Font("Microsoft YaHei UI", 10)
    $script:statusLabel.Location = New-Object System.Drawing.Point(50, 550)
    $script:statusLabel.Size = New-Object System.Drawing.Size(1000, 30)
    $script:statusLabel.BackColor = [System.Drawing.Color]::White
    $script:statusLabel.BorderStyle = [System.Windows.Forms.BorderStyle]::FixedSingle
    $script:statusLabel.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
    $script:statusLabel.ForeColor = [System.Drawing.Color]::FromArgb(52, 73, 94)
    $script:statusLabel.Padding = New-Object System.Windows.Forms.Padding(10, 0, 0, 0)
    $script:statusLabel.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right
    $form.Controls.Add($script:statusLabel)
    
    # 初始化状态
    Update-Status "PS2EXE转换工具v2.4就绪 - 简洁版，支持中文路径和调整大小" "Primary"
    
    # 显示窗体
    $form.ShowDialog() | Out-Null
}

# 程序入口
function Main {
    try {
        Write-Host "PS1转EXE工具 v2.4 - 简洁版启动中..." -ForegroundColor Green
        Write-Host "基于PS2EXE引擎，修复路径解析问题" -ForegroundColor Cyan
        Write-Host "简洁匀称的界面设计，支持调整大小" -ForegroundColor Yellow
        Write-Host ""
        
        Show-MainForm
        
    } catch {
        Write-Host "程序启动失败: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host "详细错误: $($_.ScriptStackTrace)" -ForegroundColor Red
        Read-Host "按回车键退出"
    }
}

# 启动程序
Main